<?php
/**
 * 历史数据生成采购单和付款单
 * @author angl
 */
date_default_timezone_set("Asia/Shanghai");
set_time_limit(0);
if (isset($_SERVER['REQUEST_URI'])) {
    die('error');
}

if (!defined('API_ROOT_PATH')) {
    define('API_ROOT_PATH', dirname(__FILE__));
}

require(API_ROOT_PATH . '/../inc/common.php');
require(API_ROOT_PATH . '/../inc/Config.php');
require(API_ROOT_PATH . '/../inc/MysqliDb.php');

//初始化数据库链接
function init_db()
{
    $db = new MysqliDb ([
        'host' => MYSQLDB,
        'username' => MYSQLDB_USER,
        'password' => MYSQLDB_PWD,
        'db' => MYSQLDB_DATABASE,
        'port' => 3306,
        'prefix' => 'au_',
        'charset' => 'utf8'
    ]);
    return $db;
}
$db = init_db();
$last_id = 0;
$counter = 0;
$bp_id = 23041;

while (true) {
	$list = $db->where("(result = ? OR result = ?)", [1, 4])->where("ocl_id", $last_id, ">")->get('owner_confirm_log', 500);
	if (empty($list)) {
		logUtil($counter . "条数据处理完成", 'INFO');
		exit;
	}

	//循环处理
	foreach ($list as $item) {

		$db->startTransaction();

		if ($item['result'] == 4 && $item['ocl_id'] > $bp_id) {
			$consult = $db->where('order_id', $item['order_id'])->where('consult_status', 4)->getOne("consult");
			if (empty($consult)) {
				continue;
			}
			$item['createtime'] = $consult['createtime'];
		}

		$orderId = $item['order_id'];
		$orderInfo = $db->where("order_id", $orderId)->getOne("order");
		$carInfo = $db->where('car_id', $orderInfo['car_id'])->getOne("cars");
		if ($item['result'] == 4) {
			$successPrice = $orderInfo['success_price'] + $orderInfo['company_subsidies'];
		} else {
			$successPrice = $orderInfo['success_price'];
		}

		$purchaseOrderArr = [
			'order_id' => $orderId,
			'order_no' => $orderInfo['order_no'],
			'car_id' => $orderInfo['car_id'],
			'sid' => $carInfo['sid'],
			'amount' => $successPrice,
			'emp_id' => $item['service_id'],
			'type' => $carInfo['is_self_receive'] ? '2' : '1', //判断是否自收车
			'status' => '1',
			'createtime' => $item['createtime'],
		];

		/*$res = addPurchaseOrder($purchaseOrderData);
		if ($res) {
			logUtil($item['order_id'] . " 采购单生成成功");
		}*/
		$orderStatus = $orderInfo['status'];
		$carSource = $carInfo['car_source'];
		$payStatus = $carInfo['pay_status'];
		$isSelfReceive = $carInfo['is_self_receive'];
		$sid = $carInfo['sid'];
		$carId = $carInfo['car_id'];
		$threeInOne = $carInfo['three_in_one']; //三证合一

		if($sid == 0){
			logUtil('车源:'.$carId.'的sid为0.程序处理终止');exit();
		}
		$purchaseOrder = getPurchaseOrderBySid($sid);

		if($purchaseOrder){
			echo "车源：".$sid."已生成"."\n";
			$last_id = $item['ocl_id'];
			$counter++;
			continue;
		}

		//echo $carId."\n";
		if ($carSource == 1) { //4s车源
			/*$db->commit();
			$db->rollback();*/

			if ($orderStatus == 7 || $orderStatus == 8) {
				// TODO 根据付款状态生成 相应的采购单和 付款单
				$res5 = addPurchaseOrder($purchaseOrderArr);
				/*if ($res5) {
					logUtil($item['order_id'] . " 采购单生成成功");
				}*/

				if ($payStatus == 2) { // 2 已付首款
					$map['car_id'] = $carId;
					$map['status'] = 1; // 1 已付
					$map['pay_type'] = 1; //1 首款

					$paymentData = getPaymentInfo($map);
					//$paymentData['status'] = 1; //已付
				} else {
					$map['car_id'] = $carId;
					$map['status'] = 0; // 0 未付
					$map['pay_type'] = 1; //1 首款
					$paymentData = getPaymentInfo($map);
				}

				if(!empty($paymentData)){
					if($payStatus == 2){
						$paymentData['status'] = 1; //已付
					}
					$paymentData['amount'] = $successPrice; //4s 店全款
					$paymentData['pay_type'] = 1;
					$res6 = generatorPayment($paymentData);//添加付款单

					$res7 = addPaymentRelation($res5, $res6, $paymentData['pay_type']);
					if (!$res5 || !$res6 || !$res7) {
						$db->rollback();
						echo "4s 车源".$carId."生成付款单关系数据失败";
						logUtil("4s 车源".$carId."生成付款单关系数据失败","ERR");
						$last_id = $item['ocl_id'];
						$counter++;
						continue;
						//helpJsonResult(500, "生成付款单关系数据失败");
					}
				}
			}

			if ($orderStatus == 9 || $orderStatus == 10 || $orderStatus == 11) {
				// TODO 生成已经完成的采购单 和 已付款的付款单
				$purchaseOrderArr['status'] = 3; //采购单已完成
				$res5 = addPurchaseOrder($purchaseOrderArr);

				$map['car_id'] = $carId;
				$map['status'] = 1; // 1 已付
				$map['pay_type'] = 1; //1 首款

				$paymentData = getPaymentInfo($map);
				if(!empty($paymentData)){
					$paymentData['status'] = 1; //已付
					$res6 = generatorPayment($paymentData);//添加付款单
					$res7 = addPaymentRelation($res5, $res6, $paymentData['pay_type']);
					if (!$res5 || !$res6 || !$res7) {
						$db->rollback();
						echo "4s 车源".$carId."生成采购单,付款单关系数据失败";
						logUtil("4s 车源".$carId."生成采购单,付款单关系数据失败","INFO");
						$last_id = $item['ocl_id'];
						$counter++;
						continue;
						//echo "生成付款单关系数据失败";
					}
				}
			}

			// TODO 拍单失败时，生成相应的收付款单
			if ($orderStatus == 12) {
				$purchaseOrderArr['status'] = 2; //采购单关闭
				$res5 = addPurchaseOrder($purchaseOrderArr);
				if(!$res5){
					$db->rollback();
					echo "4s 车源".$carId."生成采购单失败";
					logUtil("4s 车源".$carId."生成采购单失败","INFO");
					$last_id = $item['ocl_id'];
					$counter++;
					continue;
				}

				$fail_type = $orderInfo['fail_type'];//失败类型

				$map['car_id'] = $carId;
				$map['pay_type'] = 1; //1 首款

				$paymentData = getPaymentInfo($map);
				if(!empty($paymentData)){
					if($fail_type > 3){
						if ($paymentData['status'] == 2){
							$paymentData['status'] = 3; //作废
						}

						$paymentData['amount'] = $successPrice; //4s 店全款
						$paymentData['pay_type'] = 1;

						$res6 = generatorPayment($paymentData);//添加付款单
						$res7 = addPaymentRelation($res5, $res6, $paymentData['pay_type']);
						if (!$res5 || !$res6 || !$res7) {
							$db->rollback();
							echo "4s 车源".$carId."生成付款单关系数据失败";
							logUtil("4s 车源".$carId."生成付款单关系数据失败","ERR");
							$last_id = $item['ocl_id'];
							$counter++;
							continue;
						}
					}
				}
			}

			// TODO 拍单完成时，生成相应的收付款单
			if ($orderStatus == 13) {

				$purchaseOrderArr['status'] = 3; //采购单完成
				$result = foursCarCreatFinishedPurchase($purchaseOrderArr, $carId);
				if(!$result){
					$last_id = $item['ocl_id'];
					$counter++;
					continue;
				}
			}
		}

		if ($carSource == 2) { //个人车源

			//echo $orderStatus;die();
			if ($orderStatus == 8 || $orderStatus == 9 || $orderStatus == 10) {
				if($threeInOne == 2){
					$purchaseOrderArr['pay_status'] = 2; //个人车源，已签约之后的状态。三证不合一的。生成的采购单是，已付首款
				}
				$res5 = addPurchaseOrder($purchaseOrderArr);
				if ($payStatus == 1) { // 1 待付首款
					if ($threeInOne == 1) { //如果三证合一

						$map['car_id'] = $carId;
						$map['status'] = 0; // 0 未付
						$map['pay_type'] = 1; //1 首款

						$paymentData = getPaymentInfo($map);
						if(!empty($paymentData)){
							$paymentData['amount'] = $successPrice / 2; //个人车源 三证合一，付 50% 首款
							$paymentData['pay_type'] = 2; //采购应付（首）

							$res6 = generatorPayment($paymentData);//添加付款单
							$res7 = addPaymentRelation($res5, $res6, $paymentData['pay_type']);
							/*if($sid == '658'){
								echo "ere"."\n";
								print_r($paymentData);die();
							}*/
							if (!$res5 || !$res6 || !$res7) {
								echo "个人车源".$carId."生成采购单，付款单关系数据失败";
								logUtil("个人车源".$carId."生成采购单，付款单关系数据失败","ERR");
								$last_id = $item['ocl_id'];
								$counter++;
								continue;
							}
						}
					}
				}

				if ($payStatus == 2) { // 2 已付首款
					if ($threeInOne == 1) { //如果三证合一
						$map['car_id'] =  $carId;
						$map['status'] =  1; // 0 未付
						$map['pay_type'] =  1; //1 首款

						$paymentData = getPaymentInfo($map);
						if(!empty($paymentData)){
							$paymentData['amount'] = $successPrice / 2; //个人车源 三证合一，付 50% 首款
							$paymentData['status'] = 1; //已付
							$paymentData['pay_type'] = 2; //采购应付（首）
							$res6 = generatorPayment($paymentData);//添加付款单
							$res7 = addPaymentRelation($res5, $res6, $paymentData['pay_type']);
							if (!$res5 || !$res6 || !$res7) {
								echo "个人车源".$carId."生成采购单，付款单关系数据失败";
								logUtil("个人车源".$carId."生成采购单，付款单关系数据失败","ERR");
								$last_id = $item['ocl_id'];
								$counter++;
								continue;
							}
						}
					}
				}

				if ($payStatus == 3) { // 3 待付尾款

					if ($threeInOne == 1) { //如果三证合一 分为两步 1. 首款已付  2. 生成未付尾款
						// 生成已付首付款

						$map['car_id'] = $carId;
						$map['status'] = 1; // 1 已付
						$map['pay_type'] = 1; //1 首款

						$paymentData = getPaymentInfo($map);
						if(!empty($paymentData)){
							$paymentData['amount'] = $successPrice / 2; //个人车源 三证合一，付 50% 首款
							$paymentData['status'] = 1; //已付
							$paymentData['pay_type'] = 2; //采购应付（首）
							$res6 = generatorPayment($paymentData);//添加付款单
							$res7 = addPaymentRelation($res5, $res6, $paymentData['pay_type']);
							if (!$res5 || !$res6 || !$res7) {
								echo "个人车源".$carId."生成采购单，付款单关系数据失败";
								logUtil("个人车源".$carId."生成采购单，付款单关系数据失败","ERR");
								$last_id = $item['ocl_id'];
								$counter++;
								continue;
							}
						}

						// 生成未付尾款
						$map['car_id'] = $carId;
						$map['status'] = 0; // 0 未付
						$map['pay_type'] = 2; //2 尾款

						$paymentData = getPaymentInfo($map);
						if(!empty($paymentData)){
							$paymentData['amount'] = $successPrice / 2; //个人车源 三证合一，付 50% 尾款
							$paymentData['pay_type'] = 3; //采购应付（尾）
							$res6 = generatorPayment($paymentData);//添加付款单
							$res7 = addPaymentRelation($res5, $res6, $paymentData['pay_type']);
							if (!$res5 || !$res6 || !$res7) {
								echo "个人车源".$carId."生成采购单，付款单关系数据失败";
								logUtil("个人车源".$carId."生成采购单，付款单关系数据失败","ERR");
								$last_id = $item['ocl_id'];
								$counter++;
								continue;
							}
						}
					} else {
						// 生成未付尾款
						$map['car_id'] =  $carId;
						$map['status'] =  0; // 0 未付
						$map['pay_type'] =  2; //2 尾款

						$paymentData = getPaymentInfo($map);
						if(!empty($paymentData)){
							$paymentData['amount'] = $successPrice; //个人车源 三证不合一，付 100% 尾款
							$paymentData['pay_type'] = 3; //采购应付（尾）
							$res6 = generatorPayment($paymentData);//添加付款单
							$res7 = addPaymentRelation($res5, $res6, $paymentData['pay_type']);
							if (!$res5 || !$res6 || !$res7) {
								echo "个人车源".$carId."生成采购单，付款单关系数据失败";
								logUtil("个人车源".$carId."生成采购单，付款单关系数据失败","ERR");
								$last_id = $item['ocl_id'];
								$counter++;
								continue;
							}
						}
					}
				}

				if ($payStatus == 4) { // 4 已付尾款

					$purchaseOrderArr['status'] = 3; //采购单已完成

					if ($threeInOne == 1) { ////如果三证合一 分为两步 1. 首款已付  2. 生成已付尾款
						// 生成首付款
						$map['car_id'] = $carId;
						$map['status'] = 1; // 1 已付
						$map['pay_type'] = 1; //1 首款

						$paymentData = getPaymentInfo($map);
						if(!empty($paymentData)){
							$paymentData['amount'] = $successPrice / 2; //个人车源 三证合一，付 50% 首款
							$paymentData['status'] = 1; //已付
							$paymentData['pay_type'] = 2; //采购应付（首）
							$res6 = generatorPayment($paymentData);//添加付款单
							$res7 = addPaymentRelation($res5, $res6, $paymentData['pay_type']);
							if (!$res5 || !$res6 || !$res7) {
								echo "个人车源".$carId."生成采购单，付款单关系数据失败";
								logUtil("个人车源".$carId."生成采购单，付款单关系数据失败","ERR");
								$last_id = $item['ocl_id'];
								$counter++;
								continue;
							}
						}


						// 生成已付尾款
						$map['car_id'] = $carId;
						$map['status'] =  1; // 0 未付
						$map['pay_type'] = 2; //2 尾款

						$paymentData = getPaymentInfo($map);

						if(!empty($paymentData)){

							$paymentData['amount'] = $successPrice / 2; //个人车源 三证合一，付 50% 尾款
							$paymentData['pay_type'] = 3; //采购应付（尾）
							$paymentData['status'] = 1; //已付
							$res6 = generatorPayment($paymentData);//添加付款单
							$res7 = addPaymentRelation($res5, $res6, $paymentData['pay_type']);
							if (!$res5 || !$res6 || !$res7) {
								echo "个人车源".$carId."生成采购单，付款单关系数据失败";
								logUtil("个人车源".$carId."生成采购单，付款单关系数据失败","ERR");
								$last_id = $item['ocl_id'];
								$counter++;
								continue;
							}
						}
					} else {

						// 生成已付尾款
						$map['car_id'] = $carId;
						$map['status'] = 1; // 1 已付
						$map['pay_type'] = 2; //2 尾款

						$paymentData = getPaymentInfo($map);
						if(!empty($paymentData)){
							$paymentData['amount'] = $successPrice; //个人车源 三证不合一，付 100% 尾款
							$paymentData['pay_type'] = 3; //采购应付（尾）
							$paymentData['status'] = 1; //已付
							$res6 = generatorPayment($paymentData);//添加付款单
							$res7 = addPaymentRelation($res5, $res6, $paymentData['pay_type']);
							if (!$res5 || !$res6 || !$res7) {
								echo "个人车源".$carId."生成采购单，付款单关系数据失败";
								logUtil("个人车源".$carId."生成采购单，付款单关系数据失败","ERR");
								$last_id = $item['ocl_id'];
								$counter++;
								continue;
							}
						}

					}
				}
			}

			if ($orderStatus == 11) { //过户完成

				$purchaseOrderArr['status'] = 3; //采购单已完成
				$res5 = addPurchaseOrder($purchaseOrderArr);

				if ($threeInOne == 1) { //如果三证合一
					// 生成首付款
					$map['car_id'] =  $carId;
					$map['status'] =  1; // 1 已付
					$map['pay_type'] = 1; //2 首款

					$paymentData = getPaymentInfo($map);

					if(!empty($paymentData)){
						$paymentData['amount'] = $successPrice / 2; //个人车源 三证合一，付 50% 首款
						$paymentData['status'] = 1; //已付
						$paymentData['pay_type'] = 2; //采购应付（首）

						$res6 = generatorPayment($paymentData);//添加付款单
						$res7 = addPaymentRelation($res5, $res6, $paymentData['pay_type']);
						if (!$res5 || !$res6 || !$res7) {
							echo "个人车源".$carId."生成采购单，付款单关系数据失败";
							logUtil("个人车源".$carId."生成采购单，付款单关系数据失败","ERR");
							$last_id = $item['ocl_id'];
							$counter++;
							continue;
						}
					}


					// 生成已付尾款
					$map['car_id'] = $carId;
					$map['status'] = 1; // 1 已付
					$map['pay_type'] = 2; //2 尾款

					$paymentData = getPaymentInfo($map);
					if(!empty($paymentData)){

						$paymentData['amount'] = $successPrice / 2; //个人车源 三证合一，付 50% 尾款
						$paymentData['pay_type'] = 3; //采购应付（尾）
						$paymentData['status'] = 1; //已付
						$res6 = generatorPayment($paymentData);//添加付款单
						$res7 = addPaymentRelation($res5, $res6, $paymentData['pay_type']);
						if (!$res5 || !$res6 || !$res7) {
							echo "个人车源".$carId."生成采购单，付款单关系数据失败";
							logUtil("个人车源".$carId."生成采购单，付款单关系数据失败","ERR");
							$last_id = $item['ocl_id'];
							$counter++;
							continue;
						}
					}

				} else {

					// 生成已付尾款
					$map['car_id'] = $carId;
					$map['status'] = 1; // 1 已付
					$map['pay_type'] = 2; //2 尾款

					$paymentData = getPaymentInfo($map);
					if(!empty($paymentData)){
						$paymentData['amount'] = $successPrice; //个人车源 三证不合一，付 100% 尾款
						$paymentData['pay_type'] = 3; //采购应付（首）
						$paymentData['status'] = 1; //已付
						$res6 = generatorPayment($paymentData);//添加付款单
						$res7 = addPaymentRelation($res5, $res6, $paymentData['pay_type']);
						if (!$res5 || !$res6 || !$res7) {
							echo "个人车源".$carId."生成采购单，付款单关系数据失败";
							logUtil("个人车源".$carId."生成采购单，付款单关系数据失败","ERR");

							$last_id = $item['ocl_id'];
							$counter++;
							continue;
						}
					}
				}
			}

			if($orderStatus == 12){ //拍单关闭

				$purchaseOrderArr['status'] = 2; //采购单关闭
				$result = personalCarCreatFinishedPurchase($purchaseOrderArr,$payStatus,$threeInOne,$successPrice,$carId);
				if(!$result){
					$last_id = $item['ocl_id'];
					$counter++;
					continue;
				}
			}

			if($orderStatus == 13){ //拍单完成
				$purchaseOrderArr['status'] = 3; //采购单完成
				$result = personalCarCreatFinishedPurchase($purchaseOrderArr,$payStatus,$threeInOne,$successPrice,$carId);
				if(!$result){
					$last_id = $item['ocl_id'];
					$counter++;
					continue;
				}
			}
		}

		$db->commit();
		$last_id = $item['ocl_id'];
		$counter++;
	}
}

echo "完成";die();

/**
 * 根据车源编号得到采购单信息
 *
 * @param $sid 车辆编号
 * @return array
 */
function getPurchaseOrderBySid($sid){
	global $db;
	$data = $db->where("sid", $sid)->get('purchase_order');
	return $data;
}

/**
 * 添加采购单
 *
 * @param $data
 * @return bool
 */
function addPurchaseOrder($data)
{
    global $db;
    $data['purchase_order_nu'] = genBillsNo( "CG" , $data['type'] , $data['createtime']);
    $res = $db->insert("purchase_order",$data);
    return $res;
}


/**
 * 产生固定长度的随机字符串
 * @param $len
 * @param null $chars
 * @return string
 */
function genRandomChars($len, $chars = null)
{
    if (is_null($chars)) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    }
    mt_srand(10000000 * (double)microtime());
    for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; $i++) {
        $str .= $chars[mt_rand(0, $lc)];
    }
    return $str;
}

/**
 * 产生一个四位的随机字符串
 * @return string
 */
function gen4Chars()
{
    $strChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $numbers = "0123456789";
    $randomString = genRandomChars(3);
    if (ctype_digit($randomString)) {
        $randomString = $randomString . genRandomChars(1, $strChars);
    } elseif (ctype_alpha($randomString)) {
        $randomString = $randomString . genRandomChars(1, $numbers);
    } else {
        $randomString = $randomString . genRandomChars(1);
    }
    return $randomString;
}

/**
 * 产生一个单据编号
 * @param $type
 * @param $subType
 * @param $date
 * @return string
 */
function genBillsNo($type, $subType, $date)
{
	global $db;
    if ($subType < 10) $subType = "0" . $subType;
    $date = date("Ymd",strtotime($date));
    $orderNo = $type . $subType . $date . gen4Chars();
	if($type == 'CG'){ //如果是采购单
		$data = $db->where('purchase_order_nu',$orderNo)->getOne('purchase_order');
		if($data){
			return genBillsNo($type, $subType, $date);
		}
	}elseif($type == 'FK')//如果是付款单
	{
		$data = $db->where('payment_no',$orderNo)->getOne('payment');
		if($data){
			return genBillsNo($type, $subType, $date);
		}
	}
	return $orderNo;
}


/**
 *  根据条件得到付款信息
 *
 * @param $map
 * @return mixed
 */
function getPaymentInfo($map){
	global $db;
	if(isset($map['status'])){
		$payInfo = $db->where('car_id',$map['car_id'])
			->where('`status`',$map['status'])
			->where('pay_type',$map['pay_type'])
			->getOne('pay_log');
	}else{
		$payInfo = $db->where('car_id',$map['car_id'])
			->where('pay_type',$map['pay_type'])
			->getOne('pay_log');
	}
	//$payInfo = [];
	//$payInfo = Payment::getPayInfoByCondition($map);
	if(!empty($payInfo)){
		$employeeId = $payInfo['emp_id'];

		$employeeInfo = $db->where('emp_id',$employeeId)->getOne('employee');
		if(!empty($employeeInfo)){
			$realName = $employeeInfo['real_name'];
			$payInfo['emp_id'] = $employeeId;
			$payInfo['emp_name'] = $realName;
		}else{
			$payInfo['emp_id'] = '';
			$payInfo['emp_name'] = '';
		}

		$bankInfo = $payInfo['bank_account'];

		if(!empty($bankInfo)){
			$bankArr = json_decode($bankInfo,true);
			$payInfo['bank_name'] = $bankArr['bank_name'];
			$payInfo['card_no'] = $bankArr['card_no'];
			$payInfo['account_name'] = $bankArr['account_name'];
		}else{
			$payInfo['bank_name'] = '';
			$payInfo['card_no'] = '';
			$payInfo['account_name'] = '';
		}
		$payInfo['pay_way'] = 1; //付款方式
	}/*else{
		$paymentData['status'] = 0; //默认未付
		$paymentData['bank_name'] = '';
		$paymentData['card_no'] = '';
		$paymentData['account_name'] = '';
		$paymentData['emp_id'] = '';
		$paymentData['emp_name'] = '';
	}*/
	return $payInfo;
}

/**
 *  生成付款单
 *
 * @param $paymentData 付款单数据
 * @return mixed
 */
function generatorPayment($paymentData)
{
	global $db;
	$paymentData['pay_way'] = 1;// 现金
	$paymentData['create_time'] = date('Y-m-d H:i:s');//创建时间
	$payment_no = genBillsNo("FK", $paymentData['pay_type'] , $paymentData['create_time']);
	$data = [
		'payment_no' => $payment_no,
		'status' => $paymentData['status'],
		'pay_type' => $paymentData['pay_type'],
		'pay_way' => $paymentData['pay_way'],
		'amount' => $paymentData['amount'],
		'card_no' => empty($paymentData['card_no']) ?  '' : $paymentData['card_no'],
		'bank_name' => empty($paymentData['bank_name']) ?  '' : $paymentData['bank_name'],
		'account_name' => empty($paymentData['account_name']) ?  '' : $paymentData['account_name'],
		'create_time' => $paymentData['createtime'],
		'emp_id' => empty($paymentData['emp_id']) ?  '' : $paymentData['emp_id'],
		'emp_name' => empty($paymentData['emp_name']) ?  '' : $paymentData['emp_name'],
		'update_time' => $paymentData['last_update'],
	];
	/*if($paymentData['car_id'] == '658'){
		print_r($data);die();
	}*/
	$result = $db->insert("payment",$data);
	if(!$result){
		var_dump($result);
		var_dump($db->getLastQuery());
	}
	return $result;
}

/**
 * 添加采购单付款关系数据
 *
 * @param int $purchaseOrderId 采购单编号
 * @param int $paymentId 付款单编号
 * @param int $paymentType 付款类型
 * @return mixed
 */
function addPaymentRelation($purchaseOrderId, $paymentId, $paymentType)
{
	global $db;
	$data = [
		'po_id' => $purchaseOrderId,
		'payment_id' => $paymentId,
		'pay_type' => $paymentType,
		'createtime' => date('Y-m-d H:i:s', time()),
	];
	$result = $db->insert('purchase_payments',$data);
	if(!$result){
		var_dump($result);
		var_dump($db->getLastQuery());
	}
	return $result;
}


/**
 * 4s 车源拍单完成，生成已完成的采购单和付款单
 *
 * @param $purchaseOrderArr 采购单数据
 * @param $carId
 * @return bool
 */
function foursCarCreatFinishedPurchase($purchaseOrderArr, $carId){
	global $db;
	$purchaseOrderArr['status'] = 3; //采购单已完成
	$res5 = addPurchaseOrder($purchaseOrderArr);

	$map['car_id'] = $carId;
	$map['status'] =  1; // 1 已付
	$map['pay_type'] =  1; //1 首款

	$paymentData = getPaymentInfo($map);

	if(!empty($paymentData)){
		$paymentData['status'] = 1; //已付
		$res6 = generatorPayment($paymentData);//添加付款单
		$res7 = addPaymentRelation($res5, $res6, $paymentData['pay_type']);
		if(!$res6){
			logUtil("4s车源拍单完成，生成采购单，添加付款单 ". $carId ." 失败！ ","ERROR");
			$db->getLastQuery();
			die();
			return false;
		}

		if(!$res7){
			logUtil("4s车源拍单完成，生成采购单，添加付款单关系 ". $carId ." 失败！ ","ERROR");
			die();
			return false;
		}

		logUtil("4s车源拍单完成，生成采购单，付款单 ". $carId ." 成功！ ");
		return true;


	}
	return true;
}

/**
 * 个人车源完成采购单
 *
 * @param $purchaseOrderArr 采购单数组
 * @param $payStatus 付款状态
 * @param $threeInOne 三证合一
 * @param $successPrice 成交金额
 * @param $carId 车辆编号
 * @return bool
 */
function personalCarCreatFinishedPurchase($purchaseOrderArr, $payStatus, $threeInOne, $successPrice, $carId){
	global $db;
	$res5 = addPurchaseOrder($purchaseOrderArr);

	if ($payStatus == 1) { // 1 待付首款
		if ($threeInOne == 1) { //如果三证合一
			$paymentData['amount'] = $successPrice / 2; //个人车源 三证合一，付 50% 首款

			$map['car_id'] = $carId;
			$map['status'] = 0; // 0 未付
			$map['pay_type'] = 1; //1 首款

			$paymentData = getPaymentInfo($map);


			if(!empty($paymentData)){
				$paymentData['pay_type'] = 2; //采购应付（首）

				$res6 = generatorPayment($paymentData);//添加付款单
				/*if($carId == 703 ){
					var_dump($res6);die();
				}*/
				$res7 = addPaymentRelation($res5, $res6, $paymentData['pay_type']);
				if (!$res6 || !$res7) {
					$db->rollback();
					echo "个人车源".$carId."生成付款单关系数据失败";
					logUtil("个人车源".$carId."生成付款单关系数据失败","ERR");
					return false;
				}
			}
		}
	}

	if ($payStatus == 2) { // 2 已付首款
		if ($threeInOne == 1) { //如果三证合一
			$map['car_id'] = $carId;
			$map['status'] = 1; // 0 未付
			$map['pay_type'] = 1; //1 首款

			$paymentData = getPaymentInfo($map);
			if(!empty($paymentData)){
				$paymentData['amount'] = $successPrice / 2; //个人车源 三证合一，付 50% 首款
				$paymentData['status'] = 1; //已付
				$paymentData['pay_type'] = 2; //采购应付（首）
				$res6 = generatorPayment($paymentData);//添加付款单
				$res7 = addPaymentRelation($res5, $res6, $paymentData['pay_type']);
				if (!$res6 || !$res7) {
					echo "个人车源".$carId."生成付款单关系数据失败";
					logUtil("个人车源".$carId."生成付款单关系数据失败","ERR");
					return false;
				}
			}
		}
	}

	if ($payStatus == 3) { // 3 待付尾款

		if ($threeInOne == 1) { //如果三证合一 分为两步 1. 首款已付  2. 生成未付尾款
			// 生成已付首付款

			$map['car_id'] = $carId;
			$map['status'] = 1; // 1 已付
			$map['pay_type'] = 1; //1 首款

			$paymentData = getPaymentInfo($map);
			if(!empty($paymentData)){
				$paymentData['amount'] = $successPrice / 2; //个人车源 三证合一，付 50% 首款
				$paymentData['status'] = 1; //已付
				$paymentData['pay_type'] = 2; //采购应付（首）
				$res6 = generatorPayment($paymentData);//添加付款单
				$res7 = addPaymentRelation($res5, $res6, $paymentData['pay_type']);
				if (!$res6 || !$res7) {
					echo "个人车源".$carId."生成付款单关系数据失败";
					logUtil("个人车源".$carId."生成付款单关系数据失败","ERR");
					return false;
				}
			}


			// 生成未付尾款
			$map['car_id'] = $carId;
			$map['status'] = 0; // 0 未付
			$map['pay_type'] = 2; //2 尾款

			$paymentData = getPaymentInfo($map);
			if(!empty($paymentData)){
				$paymentData['amount'] = $successPrice / 2; //个人车源 三证合一，付 50% 尾款
				$paymentData['pay_type'] = 3; //采购应付（尾）
				$res6 = generatorPayment($paymentData);//添加付款单
				$res7 = addPaymentRelation($res5, $res6, $paymentData['pay_type']);
				if (!$res6 || !$res7) {
					echo "个人车源".$carId."生成付款单关系数据失败";
					logUtil("个人车源".$carId."生成付款单关系数据失败","ERR");
					return false;
				}
			}
		} else {
			// 生成未付尾款
			$map['car_id'] = $carId;
			$map['status'] =  0; // 0 未付
			$map['pay_type'] =  2; //2 尾款

			$paymentData = getPaymentInfo($map);
			if(!empty($paymentData)){
				$paymentData['amount'] = $successPrice; //个人车源 三证不合一，付 100% 尾款
				$paymentData['pay_type'] = 3; //采购应付（尾）
				$res6 = generatorPayment($paymentData);//添加付款单
				$res7 = addPaymentRelation($res5, $res6, $paymentData['pay_type']);
				if (!$res6 || !$res7) {
					echo "个人车源".$carId."生成付款单关系数据失败";
					logUtil("个人车源".$carId."生成付款单关系数据失败","ERR");
					return false;
				}
			}
		}
	}

	if ($payStatus == 4) { // 4 已付尾款

		$purchaseOrderArr['status'] = 3; //采购单已完成

		if ($threeInOne == 1) { ////如果三证合一 分为两步 1. 首款已付  2. 生成已付尾款
			// 生成首付款
			$map['car_id'] = $carId;
			$map['status'] =  1; // 1 已付
			$map['pay_type'] =  1; //1 首款

			$paymentData = getPaymentInfo($map);
			if(!empty($paymentData)){
				$paymentData['amount'] = $successPrice / 2; //个人车源 三证合一，付 50% 首款
				$paymentData['status'] = 1; //已付
				$paymentData['pay_type'] = 2; //采购应付（首）
				$res6 = generatorPayment($paymentData);//添加付款单
				$res7 = addPaymentRelation($res5, $res6, $paymentData['pay_type']);
				if (!$res6 || !$res7) {
					echo "个人车源".$carId."生成付款单关系数据失败";
					logUtil("个人车源".$carId."生成付款单关系数据失败","ERR");
					return false;
				}
			}


			// 生成已付尾款
			$map['car_id'] = $carId;
			$map['status'] = 1; // 0 未付
			$map['pay_type'] =  2; //2 尾款

			$paymentData = getPaymentInfo($map);
			if(!empty($paymentData)){
				$paymentData['amount'] = $successPrice / 2; //个人车源 三证合一，付 50% 尾款
				$paymentData['pay_type'] = 3; //采购应付（尾）
				$paymentData['status'] = 1; //已付
				$res6 = generatorPayment($paymentData);//添加付款单
				$res7 = addPaymentRelation($res5, $res6, $paymentData['pay_type']);
				if (!$res6 || !$res7) {
					echo "个人车源".$carId."生成付款单关系数据失败";
					logUtil("个人车源".$carId."生成付款单关系数据失败","ERR");
					return false;
				}
			}


		} else {

			// 生成已付尾款
			$map['car_id'] = $carId;
			$map['status'] =  1; // 1 已付
			$map['pay_type'] =  2; //2 尾款

			$paymentData = getPaymentInfo($map);
			if(!empty($paymentData)){
				$paymentData['amount'] = $successPrice; //个人车源 三证不合一，付 100% 尾款
				$paymentData['pay_type'] = 3; //采购应付（尾）
				$paymentData['status'] = 1; //已付
				$res6 = generatorPayment($paymentData);//添加付款单
				$res7 = addPaymentRelation($res5, $res6, $paymentData['pay_type']);
				if (!$res6 || !$res7) {
					echo "个人车源".$carId."生成付款单关系数据失败";
					logUtil("个人车源".$carId."生成付款单关系数据失败","ERR");
					return false;
				}
			}
		}
	}
	return true;
}




